C++ では、通信は 流れという静的な保存イベントではなく、 iostream ライブラリは ポリモーフィックな階層構造 を採用しており、 ifstream (ファイル)および istringstream (メモリ)は istreamから派生しています。これにより ストリーム継承が可能になります。基本となるストリーム用に設計された関数は、任意のソースからのデータを透明に処理できます。
コピー不可能な制約
ストリームはハードウェアへの一意かつ状態を持つ接続を表します。同じファイルポインタやコンソールバッファを複数のオブジェクトが競合するのを防ぐため、入出力オブジェクトは コピーまたは代入することはできません。例えば ofstream out1, out2; out1 = out2; のようなコードを試みるとコンパイラエラーになります。したがって、入出力オブジェクトは 非定数参照で渡さなければなりません。
順序付きブリッジ
ストリームはインターフェースを提供しますが、 順序付きコンテナ (vector、 list) がメモリを提供します。流れてきたデータは通常このコンテナに構造化され、速度を重視する場合は vector を選び、 list 柔軟な挿入を求める場合は
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What causes the termination of
while (cin >> i)?The stream reaching a value of 0.
Encountering end-of-file (EOF) or an invalid input type.
The buffer becoming full.
A semicolon in the input stream.
✅ Correct!
Correct. The expression evaluates to the stream itself, which in a boolean context returns false if the stream's failbit or eofbit is set.❌ Incorrect
The while loop terminates when the stream state becomes invalid, such as entering a character when an integer was expected.QUESTION 2
Identify the error:
ofstream out1, out2; out1 = out2;Logic error: Files cannot have the same name.
Syntax error: Stream assignment is prohibited.
Runtime error: Buffer overflow.
No error; this is standard C++ usage.
✅ Correct!
Stream objects are non-copyable and non-assignable to prevent ambiguous hardware management.❌ Incorrect
C++ deletes the copy constructor and assignment operator for IO classes.QUESTION 3
How should an
istream be passed to a function that reads from it?By value (e.g., void func(istream is))
By const reference (e.g., void func(const istream &is))
By non-const reference (e.g., void func(istream &is))
As a pointer to a const object.
✅ Correct!
Reading from a stream changes its internal state (e.g., position pointers), so it must be a non-const reference.❌ Incorrect
Since streams are non-copyable, 'by value' is impossible. Since reading modifies the stream, 'const reference' is invalid.QUESTION 4
What is the primary flaw in this loop?
while (iter1 < iter2) where iter is a list<int>::iterator?Lists only support
!= comparison for iterators.The loop will result in an infinite recursion.
List iterators must be decremented.
You cannot compare iterators of the same container.
✅ Correct!
Correct! Because lists are not stored contiguously, the < operator is not defined; use != instead.❌ Incorrect
The < operator is only defined for random-access iterators (like vector or deque).QUESTION 5
Why would you call
is.clear() before returning an istream& from a function?To delete all data within the stream.
To reset the error state (like EOF) so the caller can continue using it.
To flush the output buffer.
To close the associated file handle.
✅ Correct!
Once a stream hits EOF, it remains in an error state. clear() resets the state bits.❌ Incorrect
clear() affects the state flags, not the data contents or file connection.Case Study: The polymorphic Logging & Storage System
Managing Stream IO and Sequential Containers
You are designing a system that reads user input and stores it. You need a function that can read from either the standard console (cin) or a file, stores every word individually, and returns the stream to a healthy state for the next component.
Q
1. Implement Exercise 8.1: Write the C++ function that reads an istream until EOF, prints the content, and resets the stream.
Solution:
The function would look like this:
The function would look like this:
istream& readAndReset(istream &is) {
string val;
while (is >> val) {
cout << val << endl;
}
is.clear(); // Essential to reset EOF state
return is;
}Q
2. Provide a usage guide for when to select: vector, list, deque, map, and set.
Solution:
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
vector: Best for fast random access and adding elements at the end. list: Best for frequent insertions/deletions anywhere in the container. deque: Best for insertions/deletions at both ends (queues). map: Best for key-value pairs where fast lookups by key are needed. set: Best for maintaining a sorted collection of unique elements.
Q
3. Exercise 8.5: How would you modify a program to store each word of a file into a vector of strings?
Solution:
By using the extraction operator
By using the extraction operator
>>, which naturally stops at whitespace: string word;
while (inputFile >> word) {
vec.push_back(word);
} This differs from getline(), which reads whole lines including spaces.